<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Module: ActiveRecord::Associations::ClassMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
  <script type="text/javascript">
  // <![CDATA[

  function popupCode( url ) {
    window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
  }

  function toggleCode( id ) {
    if ( document.getElementById )
      elem = document.getElementById( id );
    else if ( document.all )
      elem = eval( "document.all." + id );
    else
      return false;

    elemStyle = elem.style;
    
    if ( elemStyle.display != "block" ) {
      elemStyle.display = "block"
    } else {
      elemStyle.display = "none"
    }

    return true;
  }
  
  // Make codeblocks hidden by default
  document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
  
  // ]]>
  </script>

</head>
<body>



    <div id="classHeader">
        <table class="header-table">
        <tr class="top-aligned-row">
          <td><strong>Module</strong></td>
          <td class="class-name-in-header">ActiveRecord::Associations::ClassMethods</td>
        </tr>
        <tr class="top-aligned-row">
            <td><strong>In:</strong></td>
            <td>
                <a href="../../../files/vendor/rails/activerecord/lib/active_record/associations_rb.html">
                vendor/rails/activerecord/lib/active_record/associations.rb
                </a>
        <br />
            </td>
        </tr>

        </table>
    </div>
  <!-- banner header -->

  <div id="bodyContent">



  <div id="contextContent">

    <div id="description">
      <p>
Associations are a set of macro-like class methods for tying objects
together through foreign keys. They express relationships like
&quot;Project has one Project Manager&quot; or &quot;Project belongs to a
Portfolio&quot;. Each macro adds a number of methods to the class which are
specialized according to the collection or association symbol and the
options hash. It works much the same way as Ruby&#8216;s own <tt>attr*</tt>
methods. Example:
</p>
<pre>
  class Project &lt; ActiveRecord::Base
    belongs_to              :portfolio
    has_one                 :project_manager
    has_many                :milestones
    has_and_belongs_to_many :categories
  end
</pre>
<p>
The project class now has the following methods (and more) to ease the
traversal and manipulation of its relationships:
</p>
<ul>
<li><tt>Project#portfolio, Project#portfolio=(portfolio),
Project#portfolio.nil?</tt>

</li>
<li><tt>Project#project_manager, Project#project_manager=(project_manager),
Project#project_manager.nil?,</tt>

</li>
<li><tt>Project#milestones.empty?, Project#milestones.size, Project#milestones,
Project#milestones&lt;&lt;(milestone),</tt>
<tt>Project#milestones.delete(milestone),
Project#milestones.find(milestone_id), Project#milestones.find(:all,
options),</tt> <tt>Project#milestones.build, Project#milestones.create</tt>

</li>
<li><tt>Project#categories.empty?, Project#categories.size, Project#categories,
Project#categories&lt;&lt;(category1),</tt>
<tt>Project#categories.delete(category1)</tt>

</li>
</ul>
<h3>A word of warning</h3>
<p>
Don&#8216;t create associations that have the same name as instance methods
of <a href="../Base.html">ActiveRecord::Base</a>. Since the association
adds a method with that name to its model, it will override the inherited
method and break things. For instance, <tt>attributes</tt> and
<tt>connection</tt> would be bad choices for association names.
</p>
<h2>Auto-generated methods</h2>
<h3>Singular associations (one-to-one)</h3>
<pre>
                                    |            |  belongs_to  |
  generated methods                 | belongs_to | :polymorphic | has_one
  ----------------------------------+------------+--------------+---------
  #other                            |     X      |      X       |    X
  #other=(other)                    |     X      |      X       |    X
  #build_other(attributes={})       |     X      |              |    X
  #create_other(attributes={})      |     X      |              |    X
  #other.create!(attributes={})     |            |              |    X
  #other.nil?                       |     X      |      X       |
</pre>
<h3>Collection associations (one-to-many / many-to-many)</h3>
<pre>
                                    |       |          | has_many
  generated methods                 | habtm | has_many | :through
  ----------------------------------+-------+----------+----------
  #others                           |   X   |    X     |    X
  #others=(other,other,...)         |   X   |    X     |    X
  #other_ids                        |   X   |    X     |    X
  #other_ids=(id,id,...)            |   X   |    X     |    X
  #others&lt;&lt;                         |   X   |    X     |    X
  #others.push                      |   X   |    X     |    X
  #others.concat                    |   X   |    X     |    X
  #others.build(attributes={})      |   X   |    X     |    X
  #others.create(attributes={})     |   X   |    X     |    X
  #others.create!(attributes={})    |   X   |    X     |    X
  #others.size                      |   X   |    X     |    X
  #others.length                    |   X   |    X     |    X
  #others.count                     |   X   |    X     |    X
  #others.sum(args*,&amp;block)         |   X   |    X     |    X
  #others.empty?                    |   X   |    X     |    X
  #others.clear                     |   X   |    X     |    X
  #others.delete(other,other,...)   |   X   |    X     |    X
  #others.delete_all                |   X   |    X     |
  #others.destroy_all               |   X   |    X     |    X
  #others.find(*args)               |   X   |    X     |    X
  #others.find_first                |   X   |          |
  #others.exist?                    |   X   |    X     |    X
  #others.uniq                      |   X   |    X     |    X
  #others.reset                     |   X   |    X     |    X
</pre>
<h2>Cardinality and associations</h2>
<p>
Active Record associations can be used to describe one-to-one, one-to-many
and many-to-many relationships between models. Each model uses an
association to describe its role in the relation. The <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> association is always
used in the model that has the foreign key.
</p>
<h3>One-to-one</h3>
<p>
Use <tt><a href="ClassMethods.html#M001302">has_one</a></tt> in the base,
and <tt><a href="ClassMethods.html#M001303">belongs_to</a></tt> in the
associated model.
</p>
<pre>
  class Employee &lt; ActiveRecord::Base
    has_one :office
  end
  class Office &lt; ActiveRecord::Base
    belongs_to :employee    # foreign key - employee_id
  end
</pre>
<h3>One-to-many</h3>
<p>
Use <tt><a href="ClassMethods.html#M001301">has_many</a></tt> in the base,
and <tt><a href="ClassMethods.html#M001303">belongs_to</a></tt> in the
associated model.
</p>
<pre>
  class Manager &lt; ActiveRecord::Base
    has_many :employees
  end
  class Employee &lt; ActiveRecord::Base
    belongs_to :manager     # foreign key - manager_id
  end
</pre>
<h3>Many-to-many</h3>
<p>
There are two ways to build a many-to-many relationship.
</p>
<p>
The first way uses a <tt><a
href="ClassMethods.html#M001301">has_many</a></tt> association with the
<tt>:through</tt> option and a join model, so there are two stages of
associations.
</p>
<pre>
  class Assignment &lt; ActiveRecord::Base
    belongs_to :programmer  # foreign key - programmer_id
    belongs_to :project     # foreign key - project_id
  end
  class Programmer &lt; ActiveRecord::Base
    has_many :assignments
    has_many :projects, :through =&gt; :assignments
  end
  class Project &lt; ActiveRecord::Base
    has_many :assignments
    has_many :programmers, :through =&gt; :assignments
  end
</pre>
<p>
For the second way, use <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt> in both
models. This requires a join table that has no corresponding model or
primary key.
</p>
<pre>
  class Programmer &lt; ActiveRecord::Base
    has_and_belongs_to_many :projects       # foreign keys in the join table
  end
  class Project &lt; ActiveRecord::Base
    has_and_belongs_to_many :programmers    # foreign keys in the join table
  end
</pre>
<p>
Choosing which way to build a many-to-many relationship is not always
simple. If you need to work with the relationship model as its own entity,
use <tt><a href="ClassMethods.html#M001301">has_many</a> :through</tt>. Use
<tt><a href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>
when working with legacy schemas or when you never work directly with the
relationship itself.
</p>
<h2>Is it a <tt><a href="ClassMethods.html#M001303">belongs_to</a></tt> or <tt><a href="ClassMethods.html#M001302">has_one</a></tt> association?</h2>
<p>
Both express a 1-1 relationship. The difference is mostly where to place
the foreign key, which goes on the table for the class declaring the <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> relationship. Example:
</p>
<pre>
  class User &lt; ActiveRecord::Base
    # I reference an account.
    belongs_to :account
  end

  class Account &lt; ActiveRecord::Base
    # One user references me.
    has_one :user
  end
</pre>
<p>
The tables for these classes could look something like:
</p>
<pre>
  CREATE TABLE users (
    id int(11) NOT NULL auto_increment,
    account_id int(11) default NULL,
    name varchar default NULL,
    PRIMARY KEY  (id)
  )

  CREATE TABLE accounts (
    id int(11) NOT NULL auto_increment,
    name varchar default NULL,
    PRIMARY KEY  (id)
  )
</pre>
<h2>Unsaved objects and associations</h2>
<p>
You can manipulate objects and associations before they are saved to the
database, but there is some special behavior you should be aware of, mostly
involving the saving of associated objects.
</p>
<h3>One-to-one associations</h3>
<ul>
<li>Assigning an object to a <tt><a
href="ClassMethods.html#M001302">has_one</a></tt> association automatically
saves that object and the object being replaced (if there is one), in order
to update their primary keys - except if the parent object is unsaved
(<tt>new_record? == true</tt>).

</li>
<li>If either of these saves fail (due to one of the objects being invalid) the
assignment statement returns <tt>false</tt> and the assignment is
cancelled.

</li>
<li>If you wish to assign an object to a <tt><a
href="ClassMethods.html#M001302">has_one</a></tt> association without
saving it, use the <tt>association.build</tt> method (documented below).

</li>
<li>Assigning an object to a <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> association does not
save the object, since the foreign key field belongs on the parent. It does
not save the parent either.

</li>
</ul>
<h3>Collections</h3>
<ul>
<li>Adding an object to a collection (<tt><a
href="ClassMethods.html#M001301">has_many</a></tt> or <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>)
automatically saves that object, except if the parent object (the owner of
the collection) is not yet stored in the database.

</li>
<li>If saving any of the objects being added to a collection (via <tt>push</tt>
or similar) fails, then <tt>push</tt> returns <tt>false</tt>.

</li>
<li>You can add an object to a collection without automatically saving it by
using the <tt>collection.build</tt> method (documented below).

</li>
<li>All unsaved (<tt>new_record? == true</tt>) members of the collection are
automatically saved when the parent is saved.

</li>
</ul>
<h3>Association callbacks</h3>
<p>
Similar to the normal callbacks that hook into the lifecycle of an Active
Record object, you can also define callbacks that get triggered when you
add an object to or remove an object from an association collection.
Example:
</p>
<pre>
  class Project
    has_and_belongs_to_many :developers, :after_add =&gt; :evaluate_velocity

    def evaluate_velocity(developer)
      ...
    end
  end
</pre>
<p>
It&#8216;s possible to stack callbacks by passing them as an array.
Example:
</p>
<pre>
  class Project
    has_and_belongs_to_many :developers, :after_add =&gt; [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
  end
</pre>
<p>
Possible callbacks are: <tt>before_add</tt>, <tt>after_add</tt>,
<tt>before_remove</tt> and <tt>after_remove</tt>.
</p>
<p>
Should any of the <tt>before_add</tt> callbacks throw an exception, the
object does not get added to the collection. Same with the
<tt>before_remove</tt> callbacks; if an exception is thrown the object
doesn&#8216;t get removed.
</p>
<h3>Association extensions</h3>
<p>
The proxy objects that control the access to associations can be extended
through anonymous modules. This is especially beneficial for adding new
finders, creators, and other factory-type methods that are only used as
part of this association. Example:
</p>
<pre>
  class Account &lt; ActiveRecord::Base
    has_many :people do
      def find_or_create_by_name(name)
        first_name, last_name = name.split(&quot; &quot;, 2)
        find_or_create_by_first_name_and_last_name(first_name, last_name)
      end
    end
  end

  person = Account.find(:first).people.find_or_create_by_name(&quot;David Heinemeier Hansson&quot;)
  person.first_name # =&gt; &quot;David&quot;
  person.last_name  # =&gt; &quot;Heinemeier Hansson&quot;
</pre>
<p>
If you need to share the same extensions between many associations, you can
use a named extension module. Example:
</p>
<pre>
  module FindOrCreateByNameExtension
    def find_or_create_by_name(name)
      first_name, last_name = name.split(&quot; &quot;, 2)
      find_or_create_by_first_name_and_last_name(first_name, last_name)
    end
  end

  class Account &lt; ActiveRecord::Base
    has_many :people, :extend =&gt; FindOrCreateByNameExtension
  end

  class Company &lt; ActiveRecord::Base
    has_many :people, :extend =&gt; FindOrCreateByNameExtension
  end
</pre>
<p>
If you need to use multiple named extension modules, you can specify an
array of modules with the <tt>:extend</tt> option. In the case of name
conflicts between methods in the modules, methods in modules later in the
array supercede those earlier in the array. Example:
</p>
<pre>
  class Account &lt; ActiveRecord::Base
    has_many :people, :extend =&gt; [FindOrCreateByNameExtension, FindRecentExtension]
  end
</pre>
<p>
Some extensions can only be made to work with knowledge of the association
proxy&#8216;s internals. Extensions can access relevant state using
accessors on the association proxy:
</p>
<ul>
<li><tt>proxy_owner</tt> - Returns the object the association is part of.

</li>
<li><tt>proxy_reflection</tt> - Returns the reflection object that describes
the association.

</li>
<li><tt>proxy_target</tt> - Returns the associated object for <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> and <tt><a
href="ClassMethods.html#M001302">has_one</a></tt>, or the collection of
associated objects for <tt><a
href="ClassMethods.html#M001301">has_many</a></tt> and <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>.

</li>
</ul>
<h3>Association Join Models</h3>
<p>
Has Many associations can be configured with the <tt>:through</tt> option
to use an explicit join model to retrieve the data. This operates similarly
to a <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>
association. The advantage is that you&#8216;re able to add validations,
callbacks, and extra attributes on the join model. Consider the following
schema:
</p>
<pre>
  class Author &lt; ActiveRecord::Base
    has_many :authorships
    has_many :books, :through =&gt; :authorships
  end

  class Authorship &lt; ActiveRecord::Base
    belongs_to :author
    belongs_to :book
  end

  @author = Author.find :first
  @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
  @author.books                              # selects all books by using the Authorship join model
</pre>
<p>
You can also go through a <tt><a
href="ClassMethods.html#M001301">has_many</a></tt> association on the join
model:
</p>
<pre>
  class Firm &lt; ActiveRecord::Base
    has_many   :clients
    has_many   :invoices, :through =&gt; :clients
  end

  class Client &lt; ActiveRecord::Base
    belongs_to :firm
    has_many   :invoices
  end

  class Invoice &lt; ActiveRecord::Base
    belongs_to :client
  end

  @firm = Firm.find :first
  @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
  @firm.invoices                                   # selects all invoices by going through the Client join model.
</pre>
<h3>Polymorphic Associations</h3>
<p>
Polymorphic associations on models are not restricted on what types of
models they can be associated with. Rather, they specify an interface that
a <tt><a href="ClassMethods.html#M001301">has_many</a></tt> association
must adhere to.
</p>
<pre>
  class Asset &lt; ActiveRecord::Base
    belongs_to :attachable, :polymorphic =&gt; true
  end

  class Post &lt; ActiveRecord::Base
    has_many :assets, :as =&gt; :attachable         # The :as option specifies the polymorphic interface to use.
  end

  @asset.attachable = @post
</pre>
<p>
This works by using a type column in addition to a foreign key to specify
the associated record. In the Asset example, you&#8216;d need an
<tt>attachable_id</tt> integer column and an <tt>attachable_type</tt>
string column.
</p>
<p>
Using polymorphic associations in combination with single table inheritance
(STI) is a little tricky. In order for the associations to work as
expected, ensure that you store the base model for the STI models in the
type column of the polymorphic association. To continue with the asset
example above, suppose there are guest posts and member posts that use the
posts table for STI. In this case, there must be a <tt>type</tt> column in
the posts table.
</p>
<pre>
  class Asset &lt; ActiveRecord::Base
    belongs_to :attachable, :polymorphic =&gt; true

    def attachable_type=(sType)
       super(sType.to_s.classify.constantize.base_class.to_s)
    end
  end

  class Post &lt; ActiveRecord::Base
    # because we store &quot;Post&quot; in attachable_type now :dependent =&gt; :destroy will work
    has_many :assets, :as =&gt; :attachable, :dependent =&gt; :destroy
  end

  class GuestPost &lt; Post
  end

  class MemberPost &lt; Post
  end
</pre>
<h2>Caching</h2>
<p>
All of the methods are built on a simple caching principle that will keep
the result of the last query around unless specifically instructed not to.
The cache is even shared across methods to make it even cheaper to use the
macro-added methods without worrying too much about performance at the
first go. Example:
</p>
<pre>
  project.milestones             # fetches milestones from the database
  project.milestones.size        # uses the milestone cache
  project.milestones.empty?      # uses the milestone cache
  project.milestones(true).size  # fetches milestones from the database
  project.milestones             # uses the milestone cache
</pre>
<h2>Eager loading of associations</h2>
<p>
Eager loading is a way to find objects of a certain class and a number of
named associations. This is one of the easiest ways of to prevent the
dreaded 1+N problem in which fetching 100 posts that each need to display
their author triggers 101 database queries. Through the use of eager
loading, the 101 queries can be reduced to 2. Example:
</p>
<pre>
  class Post &lt; ActiveRecord::Base
    belongs_to :author
    has_many   :comments
  end
</pre>
<p>
Consider the following loop using the class above:
</p>
<pre>
  for post in Post.all
    puts &quot;Post:            &quot; + post.title
    puts &quot;Written by:      &quot; + post.author.name
    puts &quot;Last comment on: &quot; + post.comments.first.created_on
  end
</pre>
<p>
To iterate over these one hundred posts, we&#8216;ll generate 201 database
queries. Let&#8216;s first just optimize it for retrieving the author:
</p>
<pre>
  for post in Post.find(:all, :include =&gt; :author)
</pre>
<p>
This references the name of the <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> association that also
used the <tt>:author</tt> symbol. After loading the posts, find will
collect the <tt>author_id</tt> from each one and load all the referenced
authors with one query. Doing so will cut down the number of queries from
201 to 102.
</p>
<p>
We can improve upon the situation further by referencing both associations
in the finder with:
</p>
<pre>
  for post in Post.find(:all, :include =&gt; [ :author, :comments ])
</pre>
<p>
This will load all comments with a single query. This reduces the total
number of queries to 3. More generally the number of queries will be 1 plus
the number of associations named (except if some of the associations are
polymorphic <tt><a href="ClassMethods.html#M001303">belongs_to</a></tt> -
see below).
</p>
<p>
To include a deep hierarchy of associations, use a hash:
</p>
<pre>
  for post in Post.find(:all, :include =&gt; [ :author, { :comments =&gt; { :author =&gt; :gravatar } } ])
</pre>
<p>
That&#8216;ll grab not only all the comments but all their authors and
gravatar pictures. You can mix and match symbols, arrays and hashes in any
combination to describe the associations you want to load.
</p>
<p>
All of this power shouldn&#8216;t fool you into thinking that you can pull
out huge amounts of data with no performance penalty just because
you&#8216;ve reduced the number of queries. The database still needs to
send all the data to Active Record and it still needs to be processed. So
it&#8216;s no catch-all for performance problems, but it&#8216;s a great
way to cut down on the number of queries in a situation as the one
described above.
</p>
<p>
Since only one table is loaded at a time, conditions or orders cannot
reference tables other than the main one. If this is the case Active Record
falls back to the previously used LEFT OUTER JOIN based strategy. For
example
</p>
<pre>
  Post.find(:all, :include =&gt; [ :author, :comments ], :conditions =&gt; ['comments.approved = ?', true])
</pre>
<p>
will result in a single SQL query with joins along the lines of: <tt>LEFT
OUTER JOIN comments ON comments.post_id = posts.id</tt> and <tt>LEFT OUTER
JOIN authors ON authors.id = posts.author_id</tt>. Note that using
conditions like this can have unintended consequences. In the above example
posts with no approved comments are not returned at all, because the
conditions apply to the SQL statement as a whole and not just to the
association. You must disambiguate column references for this fallback to
happen, for example <tt>:order =&gt; &quot;author.name DESC&quot;</tt> will
work but <tt>:order =&gt; &quot;name DESC&quot;</tt> will not.
</p>
<p>
If you do want eagerload only some members of an association it is usually
more natural to <tt>:include</tt> an association which has conditions
defined on it:
</p>
<pre>
  class Post &lt; ActiveRecord::Base
    has_many :approved_comments, :class_name =&gt; 'Comment', :conditions =&gt; ['approved = ?', true]
  end

  Post.find(:all, :include =&gt; :approved_comments)
</pre>
<p>
will load posts and eager load the <tt>approved_comments</tt> association,
which contains only those comments that have been approved.
</p>
<p>
If you eager load an association with a specified <tt>:limit</tt> option,
it will be ignored, returning all the associated objects:
</p>
<pre>
  class Picture &lt; ActiveRecord::Base
    has_many :most_recent_comments, :class_name =&gt; 'Comment', :order =&gt; 'id DESC', :limit =&gt; 10
  end

  Picture.find(:first, :include =&gt; :most_recent_comments).most_recent_comments # =&gt; returns all associated comments.
</pre>
<p>
When eager loaded, conditions are interpolated in the context of the model
class, not the model instance. Conditions are lazily interpolated before
the actual model exists.
</p>
<p>
Eager loading is supported with polymorphic associations.
</p>
<pre>
  class Address &lt; ActiveRecord::Base
    belongs_to :addressable, :polymorphic =&gt; true
  end
</pre>
<p>
A call that tries to eager load the addressable model
</p>
<pre>
  Address.find(:all, :include =&gt; :addressable)
</pre>
<p>
will execute one query to load the addresses and load the addressables with
one query per addressable type. For example if all the addressables are
either of class Person or Company then a total of 3 queries will be
executed. The list of addressable types to load is determined on the back
of the addresses loaded. This is not supported if Active Record has to
fallback to the previous implementation of eager loading and will raise
ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent
model&#8216;s type is a column value so its corresponding table name cannot
be put in the <tt>FROM</tt>/<tt>JOIN</tt> clauses of that query.
</p>
<h2>Table Aliasing</h2>
<p>
Active Record uses table aliasing in the case that a table is referenced
multiple times in a join. If a table is referenced only once, the standard
table name is used. The second time, the table is aliased as
<tt>#{reflection_name}_#{parent_table_name}</tt>. Indexes are appended for
any more successive uses of the table name.
</p>
<pre>
  Post.find :all, :joins =&gt; :comments
  # =&gt; SELECT ... FROM posts INNER JOIN comments ON ...
  Post.find :all, :joins =&gt; :special_comments # STI
  # =&gt; SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
  Post.find :all, :joins =&gt; [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name
  # =&gt; SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
</pre>
<p>
Acts as tree example:
</p>
<pre>
  TreeMixin.find :all, :joins =&gt; :children
  # =&gt; SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
  TreeMixin.find :all, :joins =&gt; {:children =&gt; :parent}
  # =&gt; SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
                              INNER JOIN parents_mixins ...
  TreeMixin.find :all, :joins =&gt; {:children =&gt; {:parent =&gt; :children}}
  # =&gt; SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
                              INNER JOIN parents_mixins ...
                              INNER JOIN mixins childrens_mixins_2
</pre>
<p>
Has and Belongs to Many join tables use the same idea, but add a
<tt>_join</tt> suffix:
</p>
<pre>
  Post.find :all, :joins =&gt; :categories
  # =&gt; SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
  Post.find :all, :joins =&gt; {:categories =&gt; :posts}
  # =&gt; SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
                             INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
  Post.find :all, :joins =&gt; {:categories =&gt; {:posts =&gt; :categories}}
  # =&gt; SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
                             INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
                             INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
</pre>
<p>
If you wish to specify your own custom joins using a <tt>:joins</tt>
option, those table names will take precedence over the eager associations:
</p>
<pre>
  Post.find :all, :joins =&gt; :comments, :joins =&gt; &quot;inner join comments ...&quot;
  # =&gt; SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
  Post.find :all, :joins =&gt; [:comments, :special_comments], :joins =&gt; &quot;inner join comments ...&quot;
  # =&gt; SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
                             INNER JOIN comments special_comments_posts ...
                             INNER JOIN comments ...
</pre>
<p>
Table aliases are automatically truncated according to the maximum length
of table identifiers according to the specific database.
</p>
<h2>Modules</h2>
<p>
By default, associations will look for objects within the current module
scope. Consider:
</p>
<pre>
  module MyApplication
    module Business
      class Firm &lt; ActiveRecord::Base
         has_many :clients
       end

      class Client &lt; ActiveRecord::Base; end
    end
  end
</pre>
<p>
When <tt>Firm#clients</tt> is called, it will in turn call
<tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>. If
you want to associate with a class in another module scope, this can be
done by specifying the complete class name. Example:
</p>
<pre>
  module MyApplication
    module Business
      class Firm &lt; ActiveRecord::Base; end
    end

    module Billing
      class Account &lt; ActiveRecord::Base
        belongs_to :firm, :class_name =&gt; &quot;MyApplication::Business::Firm&quot;
      end
    end
  end
</pre>
<h2>Type safety with <tt><a href="../AssociationTypeMismatch.html">ActiveRecord::AssociationTypeMismatch</a></tt></h2>
<p>
If you attempt to assign an object to an association that doesn&#8216;t
match the inferred or specified <tt>:class_name</tt>, you&#8216;ll get an
<tt><a
href="../AssociationTypeMismatch.html">ActiveRecord::AssociationTypeMismatch</a></tt>.
</p>
<h2>Options</h2>
<p>
All of the association macros can be specialized through options. This
makes cases more complex than the simple and guessable ones possible.
</p>

    </div>


   </div>

    <div id="method-list">
      <h3 class="section-bar">Methods</h3>

      <div class="name-list">
      <a href="#M001303">belongs_to</a>&nbsp;&nbsp;
      <a href="#M001304">has_and_belongs_to_many</a>&nbsp;&nbsp;
      <a href="#M001301">has_many</a>&nbsp;&nbsp;
      <a href="#M001302">has_one</a>&nbsp;&nbsp;
      </div>
    </div>

  </div>


    <!-- if includes -->

    <div id="section">





      


    <!-- if method_list -->
    <div id="methods">
      <h3 class="section-bar">Public Instance methods</h3>

      <div id="method-M001303" class="method-detail">
        <a name="M001303"></a>

        <div class="method-heading">
          <a href="#M001303" class="method-signature">
          <span class="method-name">belongs_to</span><span class="method-args">(association_id, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Specifies a one-to-one association with another class. This method should
only be used if this class contains the foreign key. If the other class
contains the foreign key, then you should use <tt><a
href="ClassMethods.html#M001302">has_one</a></tt> instead. See also <a
href="ClassMethods.html">ActiveRecord::Associations::ClassMethods</a>&#8216;s
overview on when to use <tt><a
href="ClassMethods.html#M001302">has_one</a></tt> and when to use <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt>.
</p>
<p>
Methods will be added for retrieval and query for a single associated
object, for which this object holds an id:
</p>
<dl>
<dt>association(force_reload = false)</dt><dd>Returns the associated object. <tt>nil</tt> is returned if none is found.

</dd>
<dt>association=(associate)</dt><dd>Assigns the associate object, extracts the primary key, and sets it as the
foreign key.

</dd>
<dt>association.nil?</dt><dd>Returns <tt>true</tt> if there is no associated object.

</dd>
<dt>build_association(attributes = {})</dt><dd>Returns a new object of the associated type that has been instantiated with
<tt>attributes</tt> and linked to this object through a foreign key, but
has not yet been saved.

</dd>
<dt>create_association(attributes = {})</dt><dd>Returns a new object of the associated type that has been instantiated with
<tt>attributes</tt>, linked to this object through a foreign key, and that
has already been saved (if it passed the validation).

</dd>
</dl>
<p>
(<tt>association</tt> is replaced with the symbol passed as the first
argument, so <tt><a href="ClassMethods.html#M001303">belongs_to</a>
:author</tt> would add among others <tt>author.nil?</tt>.)
</p>
<h3>Example</h3>
<p>
A Post class declares <tt><a
href="ClassMethods.html#M001303">belongs_to</a> :author</tt>, which will
add:
</p>
<ul>
<li><tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)

</li>
<li><tt>Post#author=(author)</tt> (similar to <tt>post.author_id =
author.id</tt>)

</li>
<li><tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)

</li>
<li><tt>Post#author.nil?</tt>

</li>
<li><tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)

</li>
<li><tt>Post#create_author</tt> (similar to <tt>post.author = Author.new;
post.author.save; post.author</tt>)

</li>
</ul>
<p>
The declaration can also include an options hash to specialize the behavior
of the association.
</p>
<h3>Options</h3>
<dl>
<dt>:class_name</dt><dd>Specify the class name of the association. Use it only if that name
can&#8216;t be inferred from the association name. So <tt><a
href="ClassMethods.html#M001302">has_one</a> :author</tt> will by default
be linked to the Author class, but if the real class name is Person,
you&#8216;ll have to specify it with this option.

</dd>
<dt>:conditions</dt><dd>Specify the conditions that the associated object must meet in order to be
included as a <tt>WHERE</tt> SQL fragment, such as <tt>authorized = 1</tt>.

</dd>
<dt>:select</dt><dd>By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be
changed if, for example, you want to do a join but not include the joined
columns. Do not forget to include the primary and foreign keys, otherwise
it will raise an error.

</dd>
<dt>:foreign_key</dt><dd>Specify the foreign key used for the association. By default this is
guessed to be the name of the association with an &quot;_id&quot; suffix.
So a class that defines a <tt><a
href="ClassMethods.html#M001303">belongs_to</a> :person</tt> association
will use &quot;person_id&quot; as the default <tt>:foreign_key</tt>.
Similarly, <tt><a href="ClassMethods.html#M001303">belongs_to</a>
:favorite_person, :class_name =&gt; &quot;Person&quot;</tt> will use a
foreign key of &quot;favorite_person_id&quot;.

</dd>
<dt>:dependent</dt><dd>If set to <tt>:destroy</tt>, the associated object is destroyed when this
object is. If set to <tt>:delete</tt>, the associated object is deleted
<b>without</b> calling its destroy method. This option should not be
specified when <tt><a href="ClassMethods.html#M001303">belongs_to</a></tt>
is used in conjunction with a <tt><a
href="ClassMethods.html#M001301">has_many</a></tt> relationship on another
class because of the potential to leave orphaned records behind.

</dd>
<dt>:counter_cache</dt><dd>Caches the number of belonging objects on the associate class through the
use of <tt>increment_counter</tt> and <tt>decrement_counter</tt>. The
counter cache is incremented when an object of this class is created and
decremented when it&#8216;s destroyed. This requires that a column named
<tt>#{table_name}_count</tt> (such as <tt>comments_count</tt> for a
belonging Comment class) is used on the associate class (such as a Post
class). You can also specify a custom counter cache column by providing a
column name instead of a <tt>true</tt>/<tt>false</tt> value to this option
(e.g., <tt>:counter_cache =&gt; :my_custom_counter</tt>.) Note: Specifying
a counter cache will add it to that model&#8216;s list of readonly
attributes using <tt>attr_readonly</tt>.

</dd>
<dt>:include</dt><dd>Specify second-order associations that should be eager loaded when this
object is loaded.

</dd>
<dt>:polymorphic</dt><dd>Specify this association is a polymorphic association by passing
<tt>true</tt>. Note: If you&#8216;ve enabled the counter cache, then you
may want to add the counter cache attribute to the <tt>attr_readonly</tt>
list in the associated classes (e.g. <tt>class Post; attr_readonly
:comments_count; end</tt>).

</dd>
<dt>:readonly</dt><dd>If true, the associated object is readonly through the association.

</dd>
<dt>:validate</dt><dd>If false, don&#8216;t validate the associated objects when saving the
parent object. <tt>false</tt> by default.

</dd>
</dl>
<p>
Option examples:
</p>
<pre>
  belongs_to :firm, :foreign_key =&gt; &quot;client_of&quot;
  belongs_to :author, :class_name =&gt; &quot;Person&quot;, :foreign_key =&gt; &quot;author_id&quot;
  belongs_to :valid_coupon, :class_name =&gt; &quot;Coupon&quot;, :foreign_key =&gt; &quot;coupon_id&quot;,
             :conditions =&gt; 'discounts &gt; #{payments_count}'
  belongs_to :attachable, :polymorphic =&gt; true
  belongs_to :project, :readonly =&gt; true
  belongs_to :post, :counter_cache =&gt; true
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001303-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001303-source">
<pre>
      <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 987</span>
 987:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">belongs_to</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {})
 988:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_belongs_to_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>)
 989: 
 990:         <span class="ruby-identifier">ivar</span> = <span class="ruby-node">&quot;@#{reflection.name}&quot;</span>
 991: 
 992:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">options</span>[<span class="ruby-identifier">:polymorphic</span>]
 993:           <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToPolymorphicAssociation</span>)
 994: 
 995:           <span class="ruby-identifier">method_name</span> = <span class="ruby-node">&quot;polymorphic_belongs_to_before_save_for_#{reflection.name}&quot;</span>.<span class="ruby-identifier">to_sym</span>
 996:           <span class="ruby-identifier">define_method</span>(<span class="ruby-identifier">method_name</span>) <span class="ruby-keyword kw">do</span>
 997:             <span class="ruby-identifier">association</span> = <span class="ruby-identifier">instance_variable_get</span>(<span class="ruby-identifier">ivar</span>) <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">instance_variable_defined?</span>(<span class="ruby-identifier">ivar</span>)
 998: 
 999:             <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">association</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">target</span>
1000:               <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">new_record?</span>
1001:                 <span class="ruby-identifier">association</span>.<span class="ruby-identifier">save</span>(<span class="ruby-keyword kw">true</span>)
1002:               <span class="ruby-keyword kw">end</span>
1003: 
1004:               <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">updated?</span>
1005:                 <span class="ruby-keyword kw">self</span>[<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">primary_key_name</span>] = <span class="ruby-identifier">association</span>.<span class="ruby-identifier">id</span>
1006:                 <span class="ruby-keyword kw">self</span>[<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">options</span>[<span class="ruby-identifier">:foreign_type</span>]] = <span class="ruby-identifier">association</span>.<span class="ruby-identifier">class</span>.<span class="ruby-identifier">base_class</span>.<span class="ruby-identifier">name</span>.<span class="ruby-identifier">to_s</span>
1007:               <span class="ruby-keyword kw">end</span>
1008:             <span class="ruby-keyword kw">end</span>
1009:           <span class="ruby-keyword kw">end</span>
1010:           <span class="ruby-identifier">before_save</span> <span class="ruby-identifier">method_name</span>
1011:         <span class="ruby-keyword kw">else</span>
1012:           <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToAssociation</span>)
1013:           <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:build</span>,  <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToAssociation</span>)
1014:           <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:create</span>, <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToAssociation</span>)
1015: 
1016:           <span class="ruby-identifier">method_name</span> = <span class="ruby-node">&quot;belongs_to_before_save_for_#{reflection.name}&quot;</span>.<span class="ruby-identifier">to_sym</span>
1017:           <span class="ruby-identifier">define_method</span>(<span class="ruby-identifier">method_name</span>) <span class="ruby-keyword kw">do</span>
1018:             <span class="ruby-identifier">association</span> = <span class="ruby-identifier">instance_variable_get</span>(<span class="ruby-identifier">ivar</span>) <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">instance_variable_defined?</span>(<span class="ruby-identifier">ivar</span>)
1019: 
1020:             <span class="ruby-keyword kw">if</span> <span class="ruby-operator">!</span><span class="ruby-identifier">association</span>.<span class="ruby-identifier">nil?</span>
1021:               <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">new_record?</span>
1022:                 <span class="ruby-identifier">association</span>.<span class="ruby-identifier">save</span>(<span class="ruby-keyword kw">true</span>)
1023:               <span class="ruby-keyword kw">end</span>
1024: 
1025:               <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">updated?</span>
1026:                 <span class="ruby-keyword kw">self</span>[<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">primary_key_name</span>] = <span class="ruby-identifier">association</span>.<span class="ruby-identifier">id</span>
1027:               <span class="ruby-keyword kw">end</span>
1028:             <span class="ruby-keyword kw">end</span>
1029:           <span class="ruby-keyword kw">end</span>
1030:           <span class="ruby-identifier">before_save</span> <span class="ruby-identifier">method_name</span>
1031:         <span class="ruby-keyword kw">end</span>
1032: 
1033:         <span class="ruby-comment cmt"># Create the callbacks to update counter cache</span>
1034:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:counter_cache</span>]
1035:           <span class="ruby-identifier">cache_column</span> = <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:counter_cache</span>] <span class="ruby-operator">==</span> <span class="ruby-keyword kw">true</span> <span class="ruby-operator">?</span>
1036:             <span class="ruby-node">&quot;#{self.to_s.demodulize.underscore.pluralize}_count&quot;</span> <span class="ruby-operator">:</span>
1037:             <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:counter_cache</span>]
1038: 
1039:           <span class="ruby-identifier">method_name</span> = <span class="ruby-node">&quot;belongs_to_counter_cache_after_create_for_#{reflection.name}&quot;</span>.<span class="ruby-identifier">to_sym</span>
1040:           <span class="ruby-identifier">define_method</span>(<span class="ruby-identifier">method_name</span>) <span class="ruby-keyword kw">do</span>
1041:             <span class="ruby-identifier">association</span> = <span class="ruby-identifier">send</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>)
1042:             <span class="ruby-identifier">association</span>.<span class="ruby-identifier">class</span>.<span class="ruby-identifier">increment_counter</span>(<span class="ruby-identifier">cache_column</span>, <span class="ruby-identifier">send</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">primary_key_name</span>)) <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">nil?</span>
1043:           <span class="ruby-keyword kw">end</span>
1044:           <span class="ruby-identifier">after_create</span> <span class="ruby-identifier">method_name</span>
1045: 
1046:           <span class="ruby-identifier">method_name</span> = <span class="ruby-node">&quot;belongs_to_counter_cache_before_destroy_for_#{reflection.name}&quot;</span>.<span class="ruby-identifier">to_sym</span>
1047:           <span class="ruby-identifier">define_method</span>(<span class="ruby-identifier">method_name</span>) <span class="ruby-keyword kw">do</span>
1048:             <span class="ruby-identifier">association</span> = <span class="ruby-identifier">send</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>)
1049:             <span class="ruby-identifier">association</span>.<span class="ruby-identifier">class</span>.<span class="ruby-identifier">decrement_counter</span>(<span class="ruby-identifier">cache_column</span>, <span class="ruby-identifier">send</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">primary_key_name</span>)) <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">nil?</span>
1050:           <span class="ruby-keyword kw">end</span>
1051:           <span class="ruby-identifier">before_destroy</span> <span class="ruby-identifier">method_name</span>
1052: 
1053:           <span class="ruby-identifier">module_eval</span>(
1054:             <span class="ruby-node">&quot;#{reflection.class_name}.send(:attr_readonly,\&quot;#{cache_column}\&quot;.intern) if defined?(#{reflection.class_name}) &amp;&amp; #{reflection.class_name}.respond_to?(:attr_readonly)&quot;</span>
1055:           )
1056:         <span class="ruby-keyword kw">end</span>
1057: 
1058:         <span class="ruby-identifier">add_single_associated_validation_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>) <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:validate</span>] <span class="ruby-operator">==</span> <span class="ruby-keyword kw">true</span>
1059: 
1060:         <span class="ruby-identifier">configure_dependency_for_belongs_to</span>(<span class="ruby-identifier">reflection</span>)
1061:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001304" class="method-detail">
        <a name="M001304"></a>

        <div class="method-heading">
          <a href="#M001304" class="method-signature">
          <span class="method-name">has_and_belongs_to_many</span><span class="method-args">(association_id, options = {}, &amp;extension)</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Specifies a many-to-many relationship with another class. This associates
two classes via an intermediate join table. Unless the join table is
explicitly specified as an option, it is guessed using the lexical order of
the class names. So a join between Developer and Project will give the
default join table name of &quot;developers_projects&quot; because
&quot;D&quot; outranks &quot;P&quot;. Note that this precedence is
calculated using the <tt>&lt;</tt> operator for String. This means that if
the strings are of different lengths, and the strings are equal when
compared up to the shortest length, then the longer string is considered of
higher lexical precedence than the shorter one. For example, one would
expect the tables &quot;paper_boxes&quot; and &quot;papers&quot; to
generate a join table name of &quot;papers_paper_boxes&quot; because of the
length of the name &quot;paper_boxes&quot;, but it in fact generates a join
table name of &quot;paper_boxes_papers&quot;. Be aware of this caveat, and
use the custom <tt>:join_table</tt> option if you need to.
</p>
<p>
Deprecated: Any additional fields added to the join table will be placed as
attributes when pulling records out through <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>
associations. Records returned from join tables with additional attributes
will be marked as readonly (because we can&#8216;t save changes to the
additional attributes). It&#8216;s strongly recommended that you upgrade
any associations with attributes to a real join model (see introduction).
</p>
<p>
Adds the following methods for retrieval and query:
</p>
<dl>
<dt>collection(force_reload = false)</dt><dd>Returns an array of all the associated objects. An empty array is returned
if none are found.

</dd>
<dt>collection&lt;&lt;(object, &#8230;)</dt><dd>Adds one or more objects to the collection by creating associations in the
join table (<tt>collection.push</tt> and <tt>collection.concat</tt> are
aliases to this method).

</dd>
<dt>collection.delete(object, &#8230;)</dt><dd>Removes one or more objects from the collection by removing their
associations from the join table. This does not destroy the objects.

</dd>
<dt>collection=objects</dt><dd>Replaces the collection&#8216;s content by deleting and adding objects as
appropriate.

</dd>
<dt>collection_singular_ids</dt><dd>Returns an array of the associated objects&#8217; ids.

</dd>
<dt>collection_singular_ids=ids</dt><dd>Replace the collection by the objects identified by the primary keys in
<tt>ids</tt>.

</dd>
<dt>collection.clear</dt><dd>Removes every object from the collection. This does not destroy the
objects.

</dd>
<dt>collection.empty?</dt><dd>Returns <tt>true</tt> if there are no associated objects.

</dd>
<dt>collection.size</dt><dd>Returns the number of associated objects.

</dd>
<dt>collection.find(id)</dt><dd>Finds an associated object responding to the <tt>id</tt> and that meets the
condition that it has to be associated with this object. Uses the same
rules as <a href="../Base.html#M001674">ActiveRecord::Base.find</a>.

</dd>
<dt>collection.exist?(&#8230;)</dt><dd>Checks whether an associated object with the given conditions exists. Uses
the same rules as ActiveRecord::Base.exists?.

</dd>
<dt>collection.build(attributes = {})</dt><dd>Returns a new object of the collection type that has been instantiated with
<tt>attributes</tt> and linked to this object through the join table, but
has not yet been saved.

</dd>
<dt>collection.create(attributes = {})</dt><dd>Returns a new object of the collection type that has been instantiated with
<tt>attributes</tt>, linked to this object through the join table, and that
has already been saved (if it passed the validation).

</dd>
</dl>
<p>
(<tt>collection</tt> is replaced with the symbol passed as the first
argument, so <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a>
:categories</tt> would add among others <tt>categories.empty?</tt>.)
</p>
<h3>Example</h3>
<p>
A Developer class declares <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a>
:projects</tt>, which will add:
</p>
<ul>
<li><tt>Developer#projects</tt>

</li>
<li><tt>Developer#projects&lt;&lt;</tt>

</li>
<li><tt>Developer#projects.delete</tt>

</li>
<li><tt>Developer#projects=</tt>

</li>
<li><tt>Developer#project_ids</tt>

</li>
<li><tt>Developer#project_ids=</tt>

</li>
<li><tt>Developer#projects.clear</tt>

</li>
<li><tt>Developer#projects.empty?</tt>

</li>
<li><tt>Developer#projects.size</tt>

</li>
<li><tt>Developer#projects.find(id)</tt>

</li>
<li><tt>Developer#clients.exist?(&#8230;)</tt>

</li>
<li><tt>Developer#projects.build</tt> (similar to
<tt>Project.new(&quot;project_id&quot; =&gt; id)</tt>)

</li>
<li><tt>Developer#projects.create</tt> (similar to <tt>c =
Project.new(&quot;project_id&quot; =&gt; id); c.save; c</tt>)

</li>
</ul>
<p>
The declaration may include an options hash to specialize the behavior of
the association.
</p>
<h3>Options</h3>
<dl>
<dt>:class_name</dt><dd>Specify the class name of the association. Use it only if that name
can&#8216;t be inferred from the association name. So <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a> :projects</tt>
will by default be linked to the Project class, but if the real class name
is SuperProject, you&#8216;ll have to specify it with this option.

</dd>
<dt>:join_table</dt><dd>Specify the name of the join table if the default based on lexical order
isn&#8216;t what you want. <b>WARNING:</b> If you&#8216;re overwriting the
table name of either class, the <tt>table_name</tt> method MUST be declared
underneath any <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>
declaration in order to work.

</dd>
<dt>:foreign_key</dt><dd>Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and &quot;_id&quot;
suffixed. So a Person class that makes a <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>
association will use &quot;person_id&quot; as the default
<tt>:foreign_key</tt>.

</dd>
<dt>:association_foreign_key</dt><dd>Specify the association foreign key used for the association. By default
this is guessed to be the name of the associated class in lower-case and
&quot;_id&quot; suffixed. So if the associated class is Project, the <tt><a
href="ClassMethods.html#M001304">has_and_belongs_to_many</a></tt>
association will use &quot;project_id&quot; as the default
<tt>:association_foreign_key</tt>.

</dd>
<dt>:conditions</dt><dd>Specify the conditions that the associated object must meet in order to be
included as a <tt>WHERE</tt> SQL fragment, such as <tt>authorized = 1</tt>.
Record creations from the association are scoped if a hash is used. <tt><a
href="ClassMethods.html#M001301">has_many</a> :posts, :conditions =&gt;
{:published =&gt; true}</tt> will create published posts with
<tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.

</dd>
<dt>:order</dt><dd>Specify the order in which the associated objects are returned as an
<tt>ORDER BY</tt> SQL fragment, such as <tt>last_name, first_name DESC</tt>

</dd>
<dt>:uniq</dt><dd>If true, duplicate associated objects will be ignored by accessors and
query methods.

</dd>
<dt>:finder_sql</dt><dd>Overwrite the default generated SQL statement used to fetch the association
with a manual statement

</dd>
<dt>:counter_sql</dt><dd>Specify a complete SQL statement to fetch the size of the association. If
<tt>:finder_sql</tt> is specified but not <tt>:counter_sql</tt>,
<tt>:counter_sql</tt> will be generated by replacing <tt>SELECT &#8230;
FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.

</dd>
<dt>:delete_sql</dt><dd>Overwrite the default generated SQL statement used to remove links between
the associated classes with a manual statement.

</dd>
<dt>:insert_sql</dt><dd>Overwrite the default generated SQL statement used to add links between the
associated classes with a manual statement.

</dd>
<dt>:extend</dt><dd>Anonymous module for extending the proxy, see &quot;Association
extensions&quot;.

</dd>
<dt>:include</dt><dd>Specify second-order associations that should be eager loaded when the
collection is loaded.

</dd>
<dt>:group</dt><dd>An attribute name by which the result should be grouped. Uses the <tt>GROUP
BY</tt> SQL-clause.

</dd>
<dt>:limit</dt><dd>An integer determining the limit on the number of rows that should be
returned.

</dd>
<dt>:offset</dt><dd>An integer determining the offset from where the rows should be fetched. So
at 5, it would skip the first 4 rows.

</dd>
<dt>:select</dt><dd>By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be
changed if, for example, you want to do a join but not include the joined
columns. Do not forget to include the primary and foreign keys, otherwise
it will raise an error.

</dd>
<dt>:readonly</dt><dd>If true, all the associated objects are readonly through the association.

</dd>
<dt>:validate</dt><dd>If false, don&#8216;t validate the associated objects when saving the
parent object. <tt>true</tt> by default.

</dd>
</dl>
<p>
Option examples:
</p>
<pre>
  has_and_belongs_to_many :projects
  has_and_belongs_to_many :projects, :include =&gt; [ :milestones, :manager ]
  has_and_belongs_to_many :nations, :class_name =&gt; &quot;Country&quot;
  has_and_belongs_to_many :categories, :join_table =&gt; &quot;prods_cats&quot;
  has_and_belongs_to_many :categories, :readonly =&gt; true
  has_and_belongs_to_many :active_projects, :join_table =&gt; 'developers_projects', :delete_sql =&gt;
  'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001304-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001304-source">
<pre>
      <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 1202</span>
1202:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">has_and_belongs_to_many</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {}, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
1203:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_and_belongs_to_many_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
1204: 
1205:         <span class="ruby-identifier">add_multiple_associated_validation_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>) <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:validate</span>] <span class="ruby-operator">==</span> <span class="ruby-keyword kw">false</span>
1206:         <span class="ruby-identifier">add_multiple_associated_save_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>)
1207:         <span class="ruby-identifier">collection_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasAndBelongsToManyAssociation</span>)
1208: 
1209:         <span class="ruby-comment cmt"># Don't use a before_destroy callback since users' before_destroy</span>
1210:         <span class="ruby-comment cmt"># callbacks will be executed after the association is wiped out.</span>
1211:         <span class="ruby-identifier">old_method</span> = <span class="ruby-node">&quot;destroy_without_habtm_shim_for_#{reflection.name}&quot;</span>
1212:         <span class="ruby-identifier">class_eval</span> <span class="ruby-value str">&quot;alias_method :\#{old_method}, :destroy_without_callbacks\ndef destroy_without_callbacks\n\#{reflection.name}.clear\n\#{old_method}\nend\n&quot;</span> <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">method_defined?</span>(<span class="ruby-identifier">old_method</span>)
1213: 
1214:         <span class="ruby-identifier">add_association_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span>)
1215:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001301" class="method-detail">
        <a name="M001301"></a>

        <div class="method-heading">
          <a href="#M001301" class="method-signature">
          <span class="method-name">has_many</span><span class="method-args">(association_id, options = {}, &amp;extension)</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Specifies a one-to-many association. The following methods for retrieval
and query of collections of associated objects will be added:
</p>
<dl>
<dt>collection(force_reload = false)</dt><dd>Returns an array of all the associated objects. An empty array is returned
if none are found.

</dd>
<dt>collection&lt;&lt;(object, &#8230;)</dt><dd>Adds one or more objects to the collection by setting their foreign keys to
the collection&#8216;s primary key.

</dd>
<dt>collection.delete(object, &#8230;)</dt><dd>Removes one or more objects from the collection by setting their foreign
keys to <tt>NULL</tt>. Objects will be in addition destroyed if
they&#8216;re associated with <tt>:dependent =&gt; :destroy</tt>, and
deleted if they&#8216;re associated with <tt>:dependent =&gt;
:delete_all</tt>.

</dd>
<dt>collection=objects</dt><dd>Replaces the collections content by deleting and adding objects as
appropriate.

</dd>
<dt>collection_singular_ids</dt><dd>Returns an array of the associated objects&#8217; ids

</dd>
<dt>collection_singular_ids=ids</dt><dd>Replace the collection with the objects identified by the primary keys in
<tt>ids</tt>

</dd>
<dt>collection.clear</dt><dd>Removes every object from the collection. This destroys the associated
objects if they are associated with <tt>:dependent =&gt; :destroy</tt>,
deletes them directly from the database if <tt>:dependent =&gt;
:delete_all</tt>, otherwise sets their foreign keys to <tt>NULL</tt>.

</dd>
<dt>collection.empty?</dt><dd>Returns <tt>true</tt> if there are no associated objects.

</dd>
<dt>collection.size</dt><dd>Returns the number of associated objects.

</dd>
<dt>collection.find(...)</dt><dd>Finds an associated object according to the same rules as <a
href="../Base.html#M001674">ActiveRecord::Base.find</a>.

</dd>
<dt>collection.exist?(&#8230;)</dt><dd>Checks whether an associated object with the given conditions exists. Uses
the same rules as ActiveRecord::Base.exists?.

</dd>
<dt>collection.build(attributes = {}, &#8230;)</dt><dd>Returns one or more new objects of the collection type that have been
instantiated with <tt>attributes</tt> and linked to this object through a
foreign key, but have not yet been saved. <b>Note:</b> This only works if
an associated object already exists, not if it&#8216;s <tt>nil</tt>!

</dd>
<dt>collection.create(attributes = {})</dt><dd>Returns a new object of the collection type that has been instantiated with
<tt>attributes</tt>, linked to this object through a foreign key, and that
has already been saved (if it passed the validation). <b>Note:</b> This
only works if an associated object already exists, not if it&#8216;s
<tt>nil</tt>!

</dd>
</dl>
<p>
(<b>Note</b>: <tt>collection</tt> is replaced with the symbol passed as the
first argument, so <tt><a href="ClassMethods.html#M001301">has_many</a>
:clients</tt> would add among others <tt>clients.empty?</tt>.)
</p>
<h3>Example</h3>
<p>
Example: A Firm class declares <tt><a
href="ClassMethods.html#M001301">has_many</a> :clients</tt>, which will
add:
</p>
<ul>
<li><tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions =&gt;
[&quot;firm_id = ?&quot;, id]</tt>)

</li>
<li><tt>Firm#clients&lt;&lt;</tt>

</li>
<li><tt>Firm#clients.delete</tt>

</li>
<li><tt>Firm#clients=</tt>

</li>
<li><tt>Firm#client_ids</tt>

</li>
<li><tt>Firm#client_ids=</tt>

</li>
<li><tt>Firm#clients.clear</tt>

</li>
<li><tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)

</li>
<li><tt>Firm#clients.size</tt> (similar to <tt>Client.count &quot;firm_id =
#{id}&quot;</tt>)

</li>
<li><tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions
=&gt; &quot;firm_id = #{id}&quot;)</tt>)

</li>
<li><tt>Firm#clients.exist?(:name =&gt; &#8216;ACME&#8217;)</tt> (similar to
<tt>Client.exist?(:name =&gt; &#8216;ACME&#8217;, :firm_id =&gt;
firm.id)</tt>)

</li>
<li><tt>Firm#clients.build</tt> (similar to <tt>Client.new(&quot;firm_id&quot;
=&gt; id)</tt>)

</li>
<li><tt>Firm#clients.create</tt> (similar to <tt>c =
Client.new(&quot;firm_id&quot; =&gt; id); c.save; c</tt>)

</li>
</ul>
<p>
The declaration can also include an options hash to specialize the behavior
of the association.
</p>
<h3>Supported options</h3>
<dl>
<dt>:class_name</dt><dd>Specify the class name of the association. Use it only if that name
can&#8216;t be inferred from the association name. So <tt><a
href="ClassMethods.html#M001301">has_many</a> :products</tt> will by
default be linked to the Product class, but if the real class name is
SpecialProduct, you&#8216;ll have to specify it with this option.

</dd>
<dt>:conditions</dt><dd>Specify the conditions that the associated objects must meet in order to be
included as a <tt>WHERE</tt> SQL fragment, such as <tt>price &gt; 5 AND
name LIKE &#8216;B%&#8217;</tt>. Record creations from the association are
scoped if a hash is used. <tt><a
href="ClassMethods.html#M001301">has_many</a> :posts, :conditions =&gt;
{:published =&gt; true}</tt> will create published posts with
<tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.

</dd>
<dt>:order</dt><dd>Specify the order in which the associated objects are returned as an
<tt>ORDER BY</tt> SQL fragment, such as <tt>last_name, first_name
DESC</tt>.

</dd>
<dt>:foreign_key</dt><dd>Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and &quot;_id&quot;
suffixed. So a Person class that makes a <tt><a
href="ClassMethods.html#M001301">has_many</a></tt> association will use
&quot;person_id&quot; as the default <tt>:foreign_key</tt>.

</dd>
<dt>:primary_key</dt><dd>Specify the method that returns the primary key used for the association.
By default this is <tt>id</tt>.

</dd>
<dt>:dependent</dt><dd>If set to <tt>:destroy</tt> all the associated objects are destroyed
alongside this object by calling their <tt>destroy</tt> method. If set to
<tt>:delete_all</tt> all associated objects are deleted <b>without</b>
calling their <tt>destroy</tt> method. If set to <tt>:nullify</tt> all
associated objects&#8217; foreign keys are set to <tt>NULL</tt>
<b>without</b> calling their <tt>save</tt> callbacks. *Warning:* This
option is ignored when also using the <tt>:through</tt> option.

</dd>
<dt>:finder_sql</dt><dd>Specify a complete SQL statement to fetch the association. This is a good
way to go for complex associations that depend on multiple tables. Note:
When this option is used, <tt>find_in_collection</tt> is <em>not</em>
added.

</dd>
<dt>:counter_sql</dt><dd>Specify a complete SQL statement to fetch the size of the association. If
<tt>:finder_sql</tt> is specified but not <tt>:counter_sql</tt>,
<tt>:counter_sql</tt> will be generated by replacing <tt>SELECT &#8230;
FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.

</dd>
<dt>:extend</dt><dd>Specify a named module for extending the proxy. See &quot;Association
extensions&quot;.

</dd>
<dt>:include</dt><dd>Specify second-order associations that should be eager loaded when the
collection is loaded.

</dd>
<dt>:group</dt><dd>An attribute name by which the result should be grouped. Uses the <tt>GROUP
BY</tt> SQL-clause.

</dd>
<dt>:limit</dt><dd>An integer determining the limit on the number of rows that should be
returned.

</dd>
<dt>:offset</dt><dd>An integer determining the offset from where the rows should be fetched. So
at 5, it would skip the first 4 rows.

</dd>
<dt>:select</dt><dd>By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be
changed if you, for example, want to do a join but not include the joined
columns. Do not forget to include the primary and foreign keys, otherwise
it will raise an error.

</dd>
<dt>:as</dt><dd>Specifies a polymorphic interface (See <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt>).

</dd>
<dt>:through</dt><dd>Specifies a Join Model through which to perform the query. Options for
<tt>:class_name</tt> and <tt>:foreign_key</tt> are ignored, as the
association uses the source reflection. You can only use a
<tt>:through</tt> query through a <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> or <tt><a
href="ClassMethods.html#M001301">has_many</a></tt> association on the join
model.

</dd>
<dt>:source</dt><dd>Specifies the source association name used by <tt><a
href="ClassMethods.html#M001301">has_many</a> :through</tt> queries. Only
use it if the name cannot be inferred from the association. <tt><a
href="ClassMethods.html#M001301">has_many</a> :subscribers, :through =&gt;
:subscriptions</tt> will look for either <tt>:subscribers</tt> or
<tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.

</dd>
<dt>:source_type</dt><dd>Specifies type of the source association used by <tt><a
href="ClassMethods.html#M001301">has_many</a> :through</tt> queries where
the source association is a polymorphic <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt>.

</dd>
<dt>:uniq</dt><dd>If true, duplicates will be omitted from the collection. Useful in
conjunction with <tt>:through</tt>.

</dd>
<dt>:readonly</dt><dd>If true, all the associated objects are readonly through the association.

</dd>
<dt>:validate</dt><dd>If false, don&#8216;t validate the associated objects when saving the
parent object. true by default.

</dd>
</dl>
<p>
Option examples:
</p>
<pre>
  has_many :comments, :order =&gt; &quot;posted_on&quot;
  has_many :comments, :include =&gt; :author
  has_many :people, :class_name =&gt; &quot;Person&quot;, :conditions =&gt; &quot;deleted = 0&quot;, :order =&gt; &quot;name&quot;
  has_many :tracks, :order =&gt; &quot;position&quot;, :dependent =&gt; :destroy
  has_many :comments, :dependent =&gt; :nullify
  has_many :tags, :as =&gt; :taggable
  has_many :reports, :readonly =&gt; true
  has_many :subscribers, :through =&gt; :subscriptions, :source =&gt; :user
  has_many :subscribers, :class_name =&gt; &quot;Person&quot;, :finder_sql =&gt;
      'SELECT DISTINCT people.* ' +
      'FROM people p, post_subscriptions ps ' +
      'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
      'ORDER BY p.first_name'
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001301-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001301-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 765</span>
765:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">has_many</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {}, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
766:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_many_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
767: 
768:         <span class="ruby-identifier">configure_dependency_for_has_many</span>(<span class="ruby-identifier">reflection</span>)
769: 
770:         <span class="ruby-identifier">add_multiple_associated_validation_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>) <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:validate</span>] <span class="ruby-operator">==</span> <span class="ruby-keyword kw">false</span>
771:         <span class="ruby-identifier">add_multiple_associated_save_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>)
772:         <span class="ruby-identifier">add_association_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>, <span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">options</span>)
773: 
774:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:through</span>]
775:           <span class="ruby-identifier">collection_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasManyThroughAssociation</span>)
776:         <span class="ruby-keyword kw">else</span>
777:           <span class="ruby-identifier">collection_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasManyAssociation</span>)
778:         <span class="ruby-keyword kw">end</span>
779:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001302" class="method-detail">
        <a name="M001302"></a>

        <div class="method-heading">
          <a href="#M001302" class="method-signature">
          <span class="method-name">has_one</span><span class="method-args">(association_id, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Specifies a one-to-one association with another class. This method should
only be used if the other class contains the foreign key. If the current
class contains the foreign key, then you should use <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> instead. See also <a
href="ClassMethods.html">ActiveRecord::Associations::ClassMethods</a>&#8216;s
overview on when to use <a href="ClassMethods.html#M001302">has_one</a> and
when to use <a href="ClassMethods.html#M001303">belongs_to</a>.
</p>
<p>
The following methods for retrieval and query of a single associated object
will be added:
</p>
<dl>
<dt>association(force_reload = false)</dt><dd>Returns the associated object. <tt>nil</tt> is returned if none is found.

</dd>
<dt>association=(associate)</dt><dd>Assigns the associate object, extracts the primary key, sets it as the
foreign key, and saves the associate object.

</dd>
<dt>association.nil?</dt><dd>Returns <tt>true</tt> if there is no associated object.

</dd>
<dt>build_association(attributes = {})</dt><dd>Returns a new object of the associated type that has been instantiated with
<tt>attributes</tt> and linked to this object through a foreign key, but
has not yet been saved. <b>Note:</b> This ONLY works if an association
already exists. It will NOT work if the association is <tt>nil</tt>.

</dd>
<dt>create_association(attributes = {})</dt><dd>Returns a new object of the associated type that has been instantiated with
<tt>attributes</tt>, linked to this object through a foreign key, and that
has already been saved (if it passed the validation).

</dd>
</dl>
<p>
(<tt>association</tt> is replaced with the symbol passed as the first
argument, so <tt><a href="ClassMethods.html#M001302">has_one</a>
:manager</tt> would add among others <tt>manager.nil?</tt>.)
</p>
<h3>Example</h3>
<p>
An Account class declares <tt><a
href="ClassMethods.html#M001302">has_one</a> :beneficiary</tt>, which will
add:
</p>
<ul>
<li><tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first,
:conditions =&gt; &quot;account_id = #{id}&quot;)</tt>)

</li>
<li><tt>Account#beneficiary=(beneficiary)</tt> (similar to
<tt>beneficiary.account_id = account.id; beneficiary.save</tt>)

</li>
<li><tt>Account#beneficiary.nil?</tt>

</li>
<li><tt>Account#build_beneficiary</tt> (similar to
<tt>Beneficiary.new(&quot;account_id&quot; =&gt; id)</tt>)

</li>
<li><tt>Account#create_beneficiary</tt> (similar to <tt>b =
Beneficiary.new(&quot;account_id&quot; =&gt; id); b.save; b</tt>)

</li>
</ul>
<h3>Options</h3>
<p>
The declaration can also include an options hash to specialize the behavior
of the association.
</p>
<p>
Options are:
</p>
<dl>
<dt>:class_name</dt><dd>Specify the class name of the association. Use it only if that name
can&#8216;t be inferred from the association name. So <tt><a
href="ClassMethods.html#M001302">has_one</a> :manager</tt> will by default
be linked to the Manager class, but if the real class name is Person,
you&#8216;ll have to specify it with this option.

</dd>
<dt>:conditions</dt><dd>Specify the conditions that the associated object must meet in order to be
included as a <tt>WHERE</tt> SQL fragment, such as <tt>rank = 5</tt>.

</dd>
<dt>:order</dt><dd>Specify the order in which the associated objects are returned as an
<tt>ORDER BY</tt> SQL fragment, such as <tt>last_name, first_name
DESC</tt>.

</dd>
<dt>:dependent</dt><dd>If set to <tt>:destroy</tt>, the associated object is destroyed when this
object is. If set to <tt>:delete</tt>, the associated object is deleted
<b>without</b> calling its destroy method. If set to <tt>:nullify</tt>, the
associated object&#8216;s foreign key is set to <tt>NULL</tt>. Also,
association is assigned.

</dd>
<dt>:foreign_key</dt><dd>Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and &quot;_id&quot;
suffixed. So a Person class that makes a <tt><a
href="ClassMethods.html#M001302">has_one</a></tt> association will use
&quot;person_id&quot; as the default <tt>:foreign_key</tt>.

</dd>
<dt>:primary_key</dt><dd>Specify the method that returns the primary key used for the association.
By default this is <tt>id</tt>.

</dd>
<dt>:include</dt><dd>Specify second-order associations that should be eager loaded when this
object is loaded.

</dd>
<dt>:as</dt><dd>Specifies a polymorphic interface (See <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt>).

</dd>
<dt>:select</dt><dd>By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be
changed if, for example, you want to do a join but not include the joined
columns. Do not forget to include the primary and foreign keys, otherwise
it will raise an error.

</dd>
<dt>:through</dt><dd>Specifies a Join Model through which to perform the query. Options for
<tt>:class_name</tt> and <tt>:foreign_key</tt> are ignored, as the
association uses the source reflection. You can only use a
<tt>:through</tt> query through a <tt><a
href="ClassMethods.html#M001302">has_one</a></tt> or <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt> association on the
join model.

</dd>
<dt>:source</dt><dd>Specifies the source association name used by <tt><a
href="ClassMethods.html#M001302">has_one</a> :through</tt> queries. Only
use it if the name cannot be inferred from the association. <tt><a
href="ClassMethods.html#M001302">has_one</a> :favorite, :through =&gt;
:favorites</tt> will look for a <tt>:favorite</tt> on Favorite, unless a
<tt>:source</tt> is given.

</dd>
<dt>:source_type</dt><dd>Specifies type of the source association used by <tt><a
href="ClassMethods.html#M001302">has_one</a> :through</tt> queries where
the source association is a polymorphic <tt><a
href="ClassMethods.html#M001303">belongs_to</a></tt>.

</dd>
<dt>:readonly</dt><dd>If true, the associated object is readonly through the association.

</dd>
<dt>:validate</dt><dd>If false, don&#8216;t validate the associated object when saving the parent
object. <tt>false</tt> by default.

</dd>
</dl>
<p>
Option examples:
</p>
<pre>
  has_one :credit_card, :dependent =&gt; :destroy  # destroys the associated credit card
  has_one :credit_card, :dependent =&gt; :nullify  # updates the associated records foreign key value to NULL rather than destroying it
  has_one :last_comment, :class_name =&gt; &quot;Comment&quot;, :order =&gt; &quot;posted_on&quot;
  has_one :project_manager, :class_name =&gt; &quot;Person&quot;, :conditions =&gt; &quot;role = 'project_manager'&quot;
  has_one :attachment, :as =&gt; :attachable
  has_one :boss, :readonly =&gt; :true
  has_one :club, :through =&gt; :membership
  has_one :primary_address, :through =&gt; :addressables, :conditions =&gt; [&quot;addressable.primary = ?&quot;, true], :source =&gt; :addressable
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001302-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001302-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 874</span>
874:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">has_one</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {})
875:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:through</span>]
876:           <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_one_through_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>)
877:           <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Associations</span><span class="ruby-operator">::</span><span class="ruby-constant">HasOneThroughAssociation</span>)
878:         <span class="ruby-keyword kw">else</span>
879:           <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_one_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>)
880: 
881:           <span class="ruby-identifier">ivar</span> = <span class="ruby-node">&quot;@#{reflection.name}&quot;</span>
882: 
883:           <span class="ruby-identifier">method_name</span> = <span class="ruby-node">&quot;has_one_after_save_for_#{reflection.name}&quot;</span>.<span class="ruby-identifier">to_sym</span>
884:           <span class="ruby-identifier">define_method</span>(<span class="ruby-identifier">method_name</span>) <span class="ruby-keyword kw">do</span>
885:             <span class="ruby-identifier">association</span> = <span class="ruby-identifier">instance_variable_get</span>(<span class="ruby-identifier">ivar</span>) <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">instance_variable_defined?</span>(<span class="ruby-identifier">ivar</span>)
886: 
887:             <span class="ruby-keyword kw">if</span> <span class="ruby-operator">!</span><span class="ruby-identifier">association</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-operator">&amp;&amp;</span> (<span class="ruby-identifier">new_record?</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">association</span>.<span class="ruby-identifier">new_record?</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">association</span>[<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">primary_key_name</span>] <span class="ruby-operator">!=</span> <span class="ruby-identifier">id</span>)
888:               <span class="ruby-identifier">association</span>[<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">primary_key_name</span>] = <span class="ruby-identifier">id</span>
889:               <span class="ruby-identifier">association</span>.<span class="ruby-identifier">save</span>(<span class="ruby-keyword kw">true</span>)
890:             <span class="ruby-keyword kw">end</span>
891:           <span class="ruby-keyword kw">end</span>
892:           <span class="ruby-identifier">after_save</span> <span class="ruby-identifier">method_name</span>
893: 
894:           <span class="ruby-identifier">add_single_associated_validation_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>) <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:validate</span>] <span class="ruby-operator">==</span> <span class="ruby-keyword kw">true</span>
895:           <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasOneAssociation</span>)
896:           <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:build</span>,  <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasOneAssociation</span>)
897:           <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:create</span>, <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasOneAssociation</span>)
898: 
899:           <span class="ruby-identifier">configure_dependency_for_has_one</span>(<span class="ruby-identifier">reflection</span>)
900:         <span class="ruby-keyword kw">end</span>
901:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>


    </div>


  </div>


<div id="validator-badges">
  <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>

</body>
</html>